package com.miyu.common.utils.redis;

import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

import java.time.Duration;

/**
 * 处理redis注解空间以及名称处理 增加失效时间
 * 名称+#+300 时间格式 默认单位为秒
 * @author longmy
 */
public class CacheRedisCacheManager extends RedisCacheManager {
    public CacheRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {
        super(cacheWriter, defaultCacheConfiguration);
    }

    @Override
    protected RedisCache createRedisCache(String name, RedisCacheConfiguration cacheConfig) {
        String[] cells = StringUtils.delimitedListToStringArray(name, "#");
        name = cells[0];
        String finalName = name;
        if (cells.length > 1) {
            long ttl = Long.parseLong(cells[1]);
            /*根据传参设置缓存失效时间*/
            cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl))
                    .computePrefixWith(cacheName -> finalName+":")
                    .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                    .disableCachingNullValues();
        }else{
            cacheConfig = cacheConfig
                    .computePrefixWith(cacheName -> finalName +":")
                    .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                    .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                    .disableCachingNullValues();
        }

        return super.createRedisCache(name, cacheConfig);
    }
}
